// pages/home/search/search.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    inputSearchVal:'',
    workData : null,
    isSearch : 0
  },

  showInput: function () {
    this.setData({
      inputShowed: true
    });
  },
  hideInput: function () {
    this.setData({
      inputSearchVal: "",
      inputShowed: false
    });
  },
  clearInput: function () {
    this.setData({
      inputSearchVal: ""
    });
  },
  inputTyping: function (e) {
    this.setData({
      inputSearchVal: e.detail.value
    });
  },

  bindUrlToSearch: function () {
    const inputSearchVal = this.data.inputSearchVal;
    wx.navigateTo({
      url: '../search/search',
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据
        res.eventChannel.emit('search', {
          data: inputSearchVal
        })
      }
    })
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(option){
    var inputSearchVal
    const eventChannel = this.getOpenerEventChannel()
    // 监听acceptDataFromOpenerPage事件，获取上一页面通过eventChannel传送到当前页面的数据
    try{
      eventChannel.on('search', function(data) {
        inputSearchVal = data.data;
      })
    }catch(e){
      inputSearchVal = null
    }
    
    this.setData({
      inputSearchVal : inputSearchVal
    })
    if(inputSearchVal != null){
      const db = wx.cloud.database()
      const _ = db.command
  
      db.collection('workData').where(_.or([
        { name: db.RegExp({regexp: inputSearchVal})},
        { minContent: db.RegExp({regexp: inputSearchVal})},
        { title: db.RegExp({regexp: inputSearchVal})},
        { 
          tag: {tagData: db.RegExp({regexp: inputSearchVal})},
        },
      ]))
      .get({
        success:res => {
          console.log(res.data)
          if(res.data.length != 0){
            this.setData({
              workData: res.data,
              isSearch : true
            })
          }
        },
      })
    }else{
      console.log("请输入搜索关键字")
      this.setData({
        isSearch : -1
      })
    }
  },

  bindUrlToWorkContent: function (e) {
    wx.navigateTo({
      url: '../workContent/workContent',
      success: function (res) {
        // 通过eventChannel向被打开页面传送数据
        res.eventChannel.emit('workDataId', {
          data: e.currentTarget.dataset.openid
        })
      }
    })
  }
})



// // 数据库正则对象
// db.collection('todos').where({
//   name: db.RegExp({
//     regexp: '刘'
//   })
// })
// // 原生Javascript对象
// db.collection('todos').where({
//   name: /刘/
// })